import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../function/state/ai_chat_state.dart';
import '../../function/state/user_state.dart';
import '../../function/data/ai_chat_api_service.dart';
import '../../function/model/ai_chat_message_model.dart';
import '../../function/widgets/custom_snackbar.dart';
import '../../function/widgets/login_dialog_widget.dart';

/// AI聊天页面控制器
class AiChatController extends GetxController {
  final AiChatState _aiChatState = Get.find<AiChatState>();
  final UserState _userState = Get.find<UserState>();

  final TextEditingController _messageController = TextEditingController();
  final FocusNode _messageFocusNode = FocusNode();

  @override
  void onInit() {
    super.onInit();
    // 初始化时发送欢迎消息
    _sendWelcomeMessage();
  }

  @override
  void onClose() {
    _messageController.dispose();
    _messageFocusNode.dispose();
    super.onClose();
  }

  /// 获取消息控制器
  TextEditingController get messageController => _messageController;

  /// 获取焦点节点
  FocusNode get messageFocusNode => _messageFocusNode;

  /// 获取AI聊天状态
  AiChatState get aiChatState => _aiChatState;

  /// 获取用户状态
  UserState get userState => _userState;

  /// 发送欢迎消息
  void _sendWelcomeMessage() {
    _aiChatState.addAiMessage(
      'Hello! I\'m your AI assistant. How can I help you today?',
    );
  }

  /// 发送消息
  Future<void> sendMessage() async {
    final content = _messageController.text.trim();
    if (content.isEmpty) return;

    // 检查用户是否已登录
    if (!_userState.isLoggedIn) {
      Get.dialog(const LoginDialogWidget(), barrierDismissible: true);
      return;
    }

    // 添加用户消息
    _aiChatState.addUserMessage(content);

    // 添加AI思考中的消息
    final thinkingMessageId =
        DateTime.now().millisecondsSinceEpoch.toString() + '_thinking';
    _aiChatState.addMessage(
      AiChatMessageModel(
        id: thinkingMessageId,
        messageType: AiMessageType.ai,
        content: 'thinking...',
        timestamp: DateTime.now(),
        isSending: true,
      ),
    );

    // 清空输入框
    _messageController.clear();

    try {
      // 发送消息到AI
      final response = await AiChatApiService.sendMessage(
        sessionId: _aiChatState.currentSessionId,
        content: content,
        conversationId:
            _aiChatState.currentConversationId.isNotEmpty
                ? _aiChatState.currentConversationId
                : null,
      );

      if (response.code == 1003 && response.data != null) {
        // 更新会话ID
        if (response.data!.conversationId != null) {
          _aiChatState.setConversationId(response.data!.conversationId!);
        }

        // 移除thinking消息
        _aiChatState.removeMessage(thinkingMessageId);

        // 添加AI回复
        if (response.data!.answer != null &&
            response.data!.answer!.isNotEmpty) {
          _aiChatState.addAiMessage(
            response.data!.answer!,
            conversationId: response.data!.conversationId,
            showSec: response.data!.showSec,
          );
        }
      } else {
        // 处理错误 - 移除thinking消息并显示错误
        _aiChatState.removeMessage(thinkingMessageId);
        _handleApiError(response.message);
      }
    } catch (e) {
      // 处理网络错误 - 移除thinking消息并显示错误
      _aiChatState.removeMessage(thinkingMessageId);
      _handleNetworkError(e.toString());
    }
  }

  /// 处理API错误
  void _handleApiError(String message) {
    CustomSnackBar.error('AI服务暂时不可用: $message');
  }

  /// 处理网络错误
  void _handleNetworkError(String error) {
    CustomSnackBar.error('网络连接失败: $error');
  }

  /// 重新发送消息
  Future<void> resendMessage(String messageId) async {
    // 找到要重新发送的消息
    final message = _aiChatState.allMessages.firstWhereOrNull(
      (msg) => msg.id == messageId,
    );

    if (message == null || message.messageType != AiMessageType.user) return;

    // 更新消息状态为发送中
    _aiChatState.updateMessageStatus(
      messageId,
      isSending: true,
      isFailed: false,
    );

    try {
      // 重新发送消息
      final response = await AiChatApiService.sendMessage(
        sessionId: _aiChatState.currentSessionId,
        content: message.content,
        conversationId:
            _aiChatState.currentConversationId.isNotEmpty
                ? _aiChatState.currentConversationId
                : null,
      );

      if (response.code == 1003 && response.data != null) {
        // 更新会话ID
        if (response.data!.conversationId != null) {
          _aiChatState.setConversationId(response.data!.conversationId!);
        }

        // 添加AI回复
        if (response.data!.answer != null &&
            response.data!.answer!.isNotEmpty) {
          _aiChatState.addAiMessage(
            response.data!.answer!,
            conversationId: response.data!.conversationId,
            showSec: response.data!.showSec,
          );
        }

        // 更新消息状态为成功
        _aiChatState.updateMessageStatus(
          messageId,
          isSending: false,
          isFailed: false,
        );
      } else {
        // 更新消息状态为失败
        _aiChatState.updateMessageStatus(
          messageId,
          isSending: false,
          isFailed: true,
        );
        _handleApiError(response.message);
      }
    } catch (e) {
      // 更新消息状态为失败
      _aiChatState.updateMessageStatus(
        messageId,
        isSending: false,
        isFailed: true,
      );
      _handleNetworkError(e.toString());
    }
  }

  /// 清空聊天记录
  void clearChat() {
    _aiChatState.clearSession();
    _sendWelcomeMessage();
  }

  /// 清空所有消息（用于举报后删除对话）
  void clearAllMessages() {
    _aiChatState.clearAllMessages();
  }

  /// 获取用户头像
  String getUserAvatar() {
    if (!_userState.isLoggedIn || _userState.currentUser == null) {
      return ''; // 返回空字符串，页面会显示默认图标
    }
    return _userState.currentUser!.avatar;
  }

  /// 检查是否正在发送消息
  bool get isSending => _aiChatState.isSending;
}
